import {deepCopy, isObjectValueEqual, messages} from "share/common";
import {Button, message, Modal} from "antd";
import errorMessage from "share/errorMessage";
import React from "react";


/**
 * 需求： 10758   需要给一堆表格加上批量操作
 * 发票来源与查验-发票来源     删除  启用 禁用
 * 发票管控-发票校验           删除
 * 发票管控-发票生成费用       删除
 * 发票管控-发票控件字段设置    删除
 * 价税分离规则-价税分离规则    删除
 价税分离规则-抵扣设置         删除  启用 禁用
 费用基础配置                 删除  启用 禁用
 报销设置-报销单提交管控       删除
 报销设置-报销单打印设置       删除  启用 禁用
 报销设置-付款类型            启用 禁用
 发票袋设置     						  删除  启用 禁用
 报销标准									  删除  启用 禁用
 报销单提交管控						   删除  启用 禁用
 *
 * 实际是要输出table的 footer  selection onGetData 参数,  需要处理的特殊逻辑：全选全部，点击剔除部分数据
 */

export function batchOperations(rowConfig, operations, context) {

  const { rowKey, hideDefaultSelections = true, hideSelectAll = false, hasAuthority = true } = rowConfig;
  const { isAll, total = 0, selectedIntervalRowKeys = [], selectedRowKeys = [], btnLoading = {}, data = [],
    searchParams = {} }  = context.state;

  let _btnNameList = {
    'DELETE': messages('common.delete')/*删除*/,
    'ENABLE': messages('common-1.key28')/*启用temp*/,
    'DISABLE': messages('common-1.key29')/*禁用temp*/,
  };

  let _findKey = record =>{
    return (typeof rowKey === 'string') ? record[rowKey] : rowKey(record)
  };

  let _onRowKeysChange = ({ selectedRowKeys, selectedRows, ...rest }) => {
    isAll && data.map(i => {
      if(selectedRowKeys.indexOf(_findKey(i)) === -1) {
        selectedIntervalRowKeys.push(_findKey(i));
      } else {
        selectedIntervalRowKeys.delete(_findKey(i));
      }
    });

    selectedRows && Array.isArray(selectedRows) && selectedRows.map(i => !!i.readOnly);
    context.setState({
      selectedRowKeys,
      selectedIntervalRowKeys: [...new Set(selectedIntervalRowKeys)],
      ...rest
    });
  };

  let onChange = (selectedRowKeys, selectedRows) => _onRowKeysChange({ selectedRowKeys, selectedRows });

  let onGetData = (data, { total }, tableSearchParams) => {
    let selectedIntervalRowKeysCopy = deepCopy(selectedIntervalRowKeys);
    let selectedRowKeysCopy = deepCopy(selectedRowKeys);
    if(isAll) {
      //全选全部，勾选掉不要的数据，翻页后要记住
      data.map(item => {
        if(selectedIntervalRowKeysCopy.indexOf(_findKey(item)) === -1) {
          selectedRowKeysCopy.push(_findKey(item));
        }
      });
    } else {
      //单行数据可能被删除，每次刷新列表要刷新selectedRowKeys
      data.map(item => {
        if(selectedRowKeys.indexOf(_findKey(item)) === -1) {
          selectedRowKeysCopy.delete(_findKey(item));
        }});
    }

    //筛选数据后，要清除不在筛选结果中的项，所以清除筛选后会丢失这一部分项
    !isObjectValueEqual(tableSearchParams, searchParams) && selectedIntervalRowKeys.map(key => {
      if(!data.filter(i => _findKey(i) === key).length) {
        selectedIntervalRowKeysCopy.delete(key)
      }
    });

    context.setState({
      total,
      data,
      selectedIntervalRowKeys: selectedIntervalRowKeysCopy,
      selectedRowKeys: [...new Set(selectedRowKeysCopy)],
      searchParams: tableSearchParams
    })
  };

  let _selections = [!hideSelectAll && {
    key: 'data-all',
    text: messages('common-1.key689')/*全选全部*/,
    onSelect: changeableRowKeys => _onRowKeysChange({selectedRowKeys: changeableRowKeys, isAll: true, selectedIntervalRowKeys: []})
  }, {
    key: 'page-all',
    text: messages('common-1.key690')/*全选当页*/,
    onSelect: changeableRowKeys => _onRowKeysChange({selectedRowKeys: changeableRowKeys, isAll: false})
  }];

  let _onClick = operation => {
    if(operation.type === 'DELETE') {
      Modal.confirm({
        title: operation.modalTitle || messages('common-1.key691')/*删除设置*/,
        content: operation.modalContent || messages('common-1.key692')/*确认删除该设置？*/,
        onOk: () => {
          let queryParams = {
            all: isAll,
            ...searchParams,
            ...operation.extraParams
          };
          context.setState({ btnLoading: { [operation.type]: true } });
          operation.service(queryParams, isAll ? selectedIntervalRowKeys : selectedRowKeys).then(res => {
            context.setState({
              isAll: false,
              btnLoading: { [operation.type]: false },
              selectedRowKeys: [],
              selectedIntervalRowKeys: []
            });
            operation.onOk();
            message.success(res.data.msg || (res.data.rows && res.data.rows.msg) || messages('common.operate.success')/*操作成功*/);
          }).catch(e => {
            context.setState({ btnLoading: { [operation.type]: false } });
            errorMessage(e.response);
          });
        }
      });
    } else {
      let queryParams = {
        all: isAll,
        enable: !!(operation.type === 'ENABLE'),
        ...searchParams,
        ...operation.extraParams
      };
      context.setState({ btnLoading: { [operation.type]: true } });
      operation.service(queryParams, isAll ? selectedIntervalRowKeys : selectedRowKeys).then(res => {
        context.setState({ btnLoading: { [operation.type]: false } });
        operation.onOk();
        message.success(res.data.msg || (res.data.rows && res.data.rows.msg) || messages('common.operate.success')/*操作成功*/);
      }).catch(e => {
        context.setState({ btnLoading: { [operation.type]: false } });
        errorMessage(e.response);
      });
    }
  };

  let rowSelection = {
    onChange,
    hideDefaultSelections,
    selectedRowKeys,
    selections: hideDefaultSelections ? _selections.filter(i => !!i) : null
  };

  let footer = (
    <div>
      {operations.map(operation => (
        <Button
          type="primary"
          loading={btnLoading[operation.type]}
          onClick={() => operation.onClick ? operation.onClick() : _onClick(operation)}
          disabled={isAll ? !(total - selectedIntervalRowKeys.length) : !selectedRowKeys.length}
          style={{marginRight: 10}}
          {...operation.btnProps}
        >
          {_btnNameList[operation.type] || operation.btnName}
        </Button>
      ))}
    </div>
  );

  let renderSelectedNumber = () => (
    <span>
      {messages('common-1.key27')/*已选择*/}
      <span className='advanced-table-footer-selected-number'>
        {isAll ? total - selectedIntervalRowKeys.length : selectedRowKeys.length}
      </span>
      {messages('common-1.key693')/*条*/}
    </span>
  );

  //hasAuthority 外部控制权限
  //React.Component.prototype.checkNewAuth()  菜单级的编辑权限
  return hasAuthority && React.Component.prototype.checkNewAuth() ? { rowSelection, footer, renderSelectedNumber, onGetData } : {}
}
